//
//  PhotoSelectorViewController.swift
//  PhotoSelector
//
//  Created by lv on 15/7/10.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout

private let reuseIdentifier = "Cell"
class PhotoSelectorViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载collectionView
        prepareCollectionView()
    }
    
    //MARK:- 准备collectionView
    func prepareCollectionView() {
        
        // 设置layout布局
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        view.addSubview(collectionView)
        collectionView.backgroundColor = UIColor.lightGrayColor()
        
        collectionView.dataSource = self
        collectionView.registerClass(PhotoSelectorViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.ff_Fill(view)
    }
    
    //MARK:- 懒加载
    // collectionView
    private lazy var layout = UICollectionViewFlowLayout()
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    // 照片数组
    lazy var photoes = [UIImage]()
}

//MARK:- 扩展PhotoSelectorViewController
extension PhotoSelectorViewController:UICollectionViewDataSource, PhotoSelectorViewCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoes.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorViewCell
        // 设置cell的代理
        cell.photoDelegate = self
        cell.image = (indexPath.item == photoes.count) ? nil : photoes[indexPath.item]
        return cell
    }
    
    //MARK:- PhotoSelectorViewCellDelegate
    ///  选择照片
    func photoSelectorSelectPhoto() {
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            return
        }
        
        let picker = UIImagePickerController()
        
        // 设置代理
        picker.delegate = self
        
        // modal显示
        presentViewController(picker, animated: true, completion: nil)
    }
    ///  删除照片
    func photoSelectorDeletePhoto(cell: PhotoSelectorViewCell) {
        let indexPath = collectionView.indexPathForCell(cell)
        // 删除照片
        photoes.removeAtIndex(indexPath!.item)
        
        // 刷新数据
        collectionView.reloadData()
    }
    
    /// PhotoSelectorViewCellDelegate方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        
        // 将图片添加到照片数组中
        photoes.append(image.scaleImage(300))
        
        // 刷新
        collectionView.reloadData()
        
        // 手动关闭modal出来的控制器（选择照片完成后）
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//MARK:- 自定义照片选择cell
@objc
protocol PhotoSelectorViewCellDelegate: NSObjectProtocol {
    // 选择照片
    optional func photoSelectorSelectPhoto()
    // 删除照片
    optional func photoSelectorDeletePhoto(cell: PhotoSelectorViewCell)
}

class PhotoSelectorViewCell: UICollectionViewCell {
    
    weak var photoDelegate:PhotoSelectorViewCellDelegate?
    
    /// 显示照片
    var image:UIImage?{
        didSet {
            if image != nil {
                addBtn.setImage(image, forState: UIControlState.Normal)
            }else {
                addBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                addBtn.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
                    addBtn.userInteractionEnabled = true
            }
            removeBtn.hidden = (image == nil)
            addBtn.userInteractionEnabled = (image == nil)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 准备UI
        prepareUI()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  准备UI
    private func prepareUI() {
        // 设置按钮的填充模式
        addBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        addSubview(addBtn)
        addSubview(removeBtn)
        
        // 设置布局
        addBtn.ff_Fill(self)
        removeBtn.ff_AlignInner(ff_AlignType.TopRight, referView: addBtn, size: nil)
        
        // 设置按钮监听
        addBtn.addTarget(self, action: "selectPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        removeBtn.addTarget(self, action: "deletePhoto", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 默认删除按钮不显示
        removeBtn.hidden = true
    }
    
    //MARK:- 按钮点击事件
    func selectPhoto() {
        // 有图像显示 点击无效
        if image == nil{
            photoDelegate?.photoSelectorSelectPhoto!()
        }
    }
    
    func deletePhoto() {
        print(__FUNCTION__)
        photoDelegate?.photoSelectorDeletePhoto!(self)
        
    }
    
    //MARK:- 懒加载按钮
    // 按钮
    private lazy var addBtn: UIButton = PhotoSelectorViewCell.createBtn("compose_pic_add")
    private lazy var removeBtn: UIButton = PhotoSelectorViewCell.createBtn("compose_photo_close")
    
    //MARK:- 创建按钮类方法
    private class func createBtn(imageName: String) -> UIButton {
        let btn = UIButton()
        btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
        return btn
    }
}
